<?php

namespace App\Models;


use App\Libs\DataFormat;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;


class UserClock extends Model
{

    use DataFormat;

    protected  $table='user_clock_in';

    protected $fillable = ['user_id', 'project_id', 'team_id', 'org_id','project_clock_id', 'reward_time', 'clock_in_time', ];

    public static  $formatKey = ['id'=>'int', 'reward_time'=>'string', 'clock_in_time'=>'string',  ];

    public function project()
    {
        return $this->hasOne('App\Models\Project', 'id', 'project_id');
    }

    public function user()
    {
        return $this->hasOne('App\Models\User', 'id', 'user_id');
    }

    //检查打卡
    public static function checkClock($userId, $projectId, $lng, $lat)
    {

        $userProject = UserProject::where('user_id', $userId)->where('project_id', $projectId)->where('verify_status', 1)->first();
        if(empty($userProject))
        {
            return '打卡失败,您未参加此活动';
        }

        $projectInfo = Project::where('id', $projectId)->first();


        $date =  date('Y-m-d H:i:s');
        $clockItem = DB::table('project_clock_in')->where('project_id', $projectId)->where('begin', '<=', $date)->where('end', '>=', $date)->whereRaw("id not in (select project_clock_id from user_clock_in where user_id={$userId})")->first();

        if(empty($clockItem))
        {
            return '打卡失败,该时段无活动安排,请联系活动负责人';
        }

        $hasClock = UserClock::where('user_id', $userId)->where('project_clock_id', $clockItem->id)->first();
        if(!empty($hasClock))
        {
            return '您已成功打卡,请勿重复打卡';
        }

        $radLat1 = deg2rad($lat); //deg2rad()函数将角度转换为弧度
        $radLat2 = deg2rad($clockItem->lat);
        $radLng1 = deg2rad($lng);
        $radLng2 = deg2rad($clockItem->lng);
        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;
        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137 * 1000;
        $radius = $clockItem->distance * 1000;
        if($s > $radius)
        {
            return '打卡失败,您离活动目的地距离过远,请到达目的地后打卡';
        }

        return $clockItem->id;
    }


}
